package com.example.admin.androidtest.threadpool;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class NetWorkUtil {
    private static AppThreadManager network = AppThreadManager.get();


    public static String get(Map<String, String> map, String url) throws ExecutionException, InterruptedException {
        //通过submit得到具体执行 call方法的Future任务处理对象
        Future f1 = network.submit(new GetResult(map, url));
        //调用get()进行任务处理，并得到处理结果
        return (String) f1.get();
    }

    public static void get(Map<String, String> map, String url, Callback callback) throws ExecutionException, InterruptedException {
        /*//Callable和Future，一个产生结果，一个拿到结果
        //通过submit得到具体执行 call方法的Future任务处理对象
        Future f1 = network.submit(new GetResult(map, url));
        //调用get()进行任务处理，并得到处理结果
        String result = (String) f1.get();
        if (callback != null) {
            callback.onCallback(result);
        }*/
        network.submit(new GetResult(map, url, callback));
    }

    public interface Callback {
        void onCallback(String result);
    }

    static class GetResult implements Callable<String> {

        //post请求的参数
        private Map<String, String> map = new HashMap<>();
        //post请求的接口地址
        private String url;
        private Callback callback;


        //私有构造方法，初始化参数
        private GetResult(Map<String, String> map, String url) {
            this.map = map;
            this.url = url;
        }

        private GetResult(Map<String, String> map, String url, Callback callback) {
            this.map = map;
            this.url = url;
            this.callback = callback;
        }

        //重写的call方法
        @Override
        public String call() throws Exception {
            //这里我们做一个post请求
            //return HttpPost.getRequestData(map, url);
            //模拟网络请求
            System.out.println("thread:" + Thread.currentThread().getName());
            Thread.sleep(5000);
            String result = "{\"code\":1}";
            if (callback != null) {
                callback.onCallback(result);
            }
            return result;
        }

        /*//静态方法，用于处理post请求，并返回处理结果
        public static String getResult(Map<String, String> map, String url) {
            GetResult getResult = new GetResult(map, url);
            Future f1 = network.submit(getResult);
            String r = null;
            try {
                r = (String) (f1.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            return r;
        }*/
    }
}
